import React, { useState, useContext, useEffect } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { FaGithub, FaGoogle } from 'react-icons/fa';
import { AuthContext } from '../contexts/AuthContext';

const Login = () => {
  const { login, isAuthenticated, error: authError } = useContext(AuthContext);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [loginError, setLoginError] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();
  
  const from = location.state?.from?.pathname || '/';
  
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  
  useEffect(() => {
    // 如果已经登录，重定向到首页或来源页面
    if (isAuthenticated) {
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, from]);
  
  useEffect(() => {
    if (authError) {
      setLoginError(authError);
    }
  }, [authError]);
  
  const onSubmit = async (data) => {
    setIsSubmitting(true);
    setLoginError(null);
    
    try {
      const success = await login(data.usernameOrEmail, data.password);
      if (success) {
        navigate(from, { replace: true });
      }
    } catch (err) {
      setLoginError('登录失败，请检查您的凭据');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  return (
    <div className="flex justify-center items-center py-12">
      <div className="max-w-md w-full space-y-8 card p-8">
        <div className="text-center">
          <h2 className="text-3xl font-extrabold text-dark-800 dark:text-dark-200">
            登录账号
          </h2>
          <p className="mt-2 text-sm text-dark-500 dark:text-dark-400">
            或{' '}
            <Link to="/register" className="text-primary-600 dark:text-primary-400 hover:underline">
              注册新账号
            </Link>
          </p>
        </div>
        
        {loginError && (
          <div className="bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-200 p-3 rounded-md text-sm">
            {loginError}
          </div>
        )}
        
        <form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-4">
            <div>
              <label htmlFor="usernameOrEmail" className="label">
                用户名或邮箱
              </label>
              <input
                id="usernameOrEmail"
                name="usernameOrEmail"
                type="text"
                autoComplete="username"
                className={`input ${errors.usernameOrEmail ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('usernameOrEmail', { 
                  required: '请输入用户名或邮箱' 
                })}
              />
              {errors.usernameOrEmail && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.usernameOrEmail.message}
                </p>
              )}
            </div>
            
            <div>
              <label htmlFor="password" className="label">
                密码
              </label>
              <input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                className={`input ${errors.password ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('password', { 
                  required: '请输入密码' 
                })}
              />
              {errors.password && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.password.message}
                </p>
              )}
            </div>
          </div>
          
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <input
                id="remember-me"
                name="remember-me"
                type="checkbox"
                className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
              />
              <label htmlFor="remember-me" className="ml-2 block text-sm text-dark-600 dark:text-dark-300">
                记住我
              </label>
            </div>
            
            <div className="text-sm">
              <Link to="/forgot-password" className="text-primary-600 dark:text-primary-400 hover:underline">
                忘记密码?
              </Link>
            </div>
          </div>
          
          <div>
            <button
              type="submit"
              disabled={isSubmitting}
              className="btn btn-primary w-full flex justify-center items-center"
            >
              {isSubmitting ? (
                <span className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white mr-2"></span>
              ) : null}
              登录
            </button>
          </div>
        </form>
        
        <div className="mt-6">
          <div className="relative">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300 dark:border-dark-600"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-white dark:bg-dark-800 text-gray-500 dark:text-gray-400">
                或通过以下方式登录
              </span>
            </div>
          </div>
          
          <div className="mt-6 grid grid-cols-2 gap-3">
            <div>
              <button
                type="button"
                className="w-full flex items-center justify-center btn bg-gray-100 dark:bg-dark-700 text-dark-700 dark:text-dark-300 hover:bg-gray-200 dark:hover:bg-dark-600"
              >
                <FaGithub className="w-5 h-5 mr-2" />
                <span>GitHub</span>
              </button>
            </div>
            
            <div>
              <button
                type="button"
                className="w-full flex items-center justify-center btn bg-gray-100 dark:bg-dark-700 text-dark-700 dark:text-dark-300 hover:bg-gray-200 dark:hover:bg-dark-600"
              >
                <FaGoogle className="w-5 h-5 mr-2" />
                <span>Google</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login; 